package com.example.demo.filter;

import com.example.demo.pojo.User;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;


//@Component  // 这里暂不启用过滤器
public class TokenFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        if ("/login".equalsIgnoreCase(httpServletRequest.getRequestURI())) {
            // 访问login接口不受限
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //进行权限控制
        User user = (User) httpServletRequest.getSession().getAttribute("user");
        if (Objects.nonNull(user)) {
            //用户已登录
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write("请先登录");
        writer.flush();
        writer.close();
    }
}
